package com.fzt.reggie.controller;

/*
用于文件上传和下载
 */

import com.fzt.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RequestMapping("/common")
@RestController
@Slf4j
public class CommonChomtroller {

    @Value("${reggie.path}")
    private String basePath;
    /*
    文件上传
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info(file.toString());

        //获得上传文件的原始文件名
        String originalFilename = file.getOriginalFilename();

        //获得文件名后缀
        /*String[] split = originalFilename.split("\\.");
        String s = split[split.length - 1];
        System.out.println(s);*/
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用uuid重新生成文件名，防止覆盖
        String fileName = UUID.randomUUID().toString() + suffix;
        //System.out.println(fileName);
        //判断当前目录是否存在
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        //将文件保存到指定目录
        try {
            file.transferTo(new File(basePath  + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }


    @GetMapping("/download")
    public void dowmload(String name, HttpServletResponse response){

        try {
            //输入流：冲服务端读取需要下载的文件
            FileInputStream is = new FileInputStream(new File(basePath + name));
            //输出流，想客户端输出需要下载的数据
            ServletOutputStream outputStream = response.getOutputStream();

            //设置响应的格式
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ( (len=is.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            is.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /*
    添加菜品
     */
    //public R<String>


}
